<template>
  <d2-container class="page">
    <!-- 搜索框 -->
    <el-form ref="searchForm" :model="searchInfo" :inline="true" :label-position="position">
      <el-form-item>
        <el-input v-model="searchInfo.name" placeholder="用户名" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-select v-model="searchInfo.deptId" placeholder="选择部门" clearable>
          <el-option
            v-for="item in deptTreeData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button plain size="medium" @click="handleCurrentChange(1)" icon="fa fa-search">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮组 -->
    <el-row :gutter="2">
      <div class="avue-crud__menu">
        <div class="avue-crud__left">
          <button
            type="button"
            @click="handlerAddNew"
            class="el-button filter-item el-button--success el-button--mini"
          >
            <i class="fa fa-plus"></i>
            <span>新增</span>
          </button>
          <button
            type="button"
            @click="handlerEdit"
            class="el-button filter-item el-button--primary el-button--mini"
          >
            <i class="fa fa-edit"></i>
            <span>修改</span>
          </button>
          <button
            type="button"
            @click="handleDeleteIds"
            class="el-button filter-item el-button--danger el-button--mini"
          >
            <i class="fa fa-remove"></i>
            <span>删除</span>
          </button>
          <button type="button" class="el-button filter-item el-button--warning el-button--mini">
            <i class="fa fa-download"></i>
            <span>导出</span>
          </button>
        </div>
        <div class="avue-crud__right">
          <button
            type="button"
            class="el-button el-tooltip el-button--default el-button--small is-circle"
            aria-describedby="el-tooltip-2497"
            tabindex="0"
            title="刷新"
            @click="handleFlash"
          >
            <i class="el-icon-refresh"></i>
          </button>
        </div>
      </div>
    </el-row>
    <!-- 表格展示 -->
    <el-col :span="24">
      <el-card shadow="never" :body-style="{padding:0}">
        <div slot="header" class="clearfix">
          <span>用户列表</span>
        </div>
        <el-table
          v-loading="roleLoading"
          :data="userList"
          style="width: 100%;"
          ref="userTable"
          border
          :fit="true"
          highlight-current-row
          :header-cell-style="{'text-align':'center'}"
          @row-click="roleTableRowClick"
        >
          <el-table-column
            sortable
            resizable
            :show-overflow-tooltip="true"
            align="center"
            type="selection"
          ></el-table-column>
          <el-table-column
            prop="name"
            label="用户名称"
            width="150px"
            sortable
            resizable
            :show-overflow-tooltip="true"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="dept"
            label="所属部门"
            width="150px"
            sortable
            resizable
            :show-overflow-tooltip="true"
            align="center"
          ></el-table-column>
          <el-table-column
          prop="createTime"
          width="200px"
          label="创建时间"
          align="center"
          sortable
          show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="updateTime"
            width="200px"
            label="更新时间"
            align="center"
            sortable
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            label="操作"
            sortable
            resizable
            :show-overflow-tooltip="false"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                title="修改"
                @click="handlerUpdate(scope.row)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
              >用户信息</el-button>
              <el-button
                title="删除"
                @click="handlerRemove(scope.row)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
              ></el-button>
               <el-button
                title="重置密码"
                @click="handleResetPassword(scope.row)"
                type="danger"
                icon="el-icon-refresh-left"
                size="mini"
              >重置密码</el-button>
              <el-button
                title="修改角色"
                @click="handleChangeRole(scope.row)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
              >角色</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          align="right"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchInfo.currentPage"
          :page-sizes="pageSize"
          :page-size="searchInfo.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="searchInfo.total"
        ></el-pagination>
      </el-card>
    </el-col>
    <!-- 弹出框 -->
    <el-dialog
      title="用户信息"
      :before-close="handleDialogClose"
      :visible.sync="dialogTableVisible"
      :destroy-on-close="!dialogTableVisible"
    >
      <el-form
        label-width="auto"
        :model="userInfo"
        :label-position="position"
        ref="userForm"
        required-asterisk
        :rules="roleRules"
        center
      >
        <el-form-item required label="用户名称：" prop="name">
          <el-input v-model="userInfo.name" clearable></el-input>
        </el-form-item>
        <el-form-item v-if="!isUpdate" required label="用户密码：" prop="name">
          <el-input v-model="userInfo.password" clearable></el-input>
        </el-form-item>
        <el-form-item required label="数据范围：">
          <el-select v-model="userInfo.deptId" placeholder="选择部门" clearable>
          <el-option
            v-for="item in deptTreeData"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        </el-form-item>
        <!-- <el-form-item label="备注：" prop="description">
          <el-input type="textarea" v-model="userInfo.description" placeholder="备注" clearable></el-input>
        </el-form-item> -->
        <el-form-item required label="角色状态：" prop="status">
          <el-radio-group v-model="userInfo.status">
            <el-radio
              v-for="item in isEnabledOptions "
              :key="item.value"
              :label="item.value"
            >{{item.desc}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlerSave" size="medium" plain>保存</el-button>
        <el-button size="medium" @click="handleDialogClose" plain>取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改角色弹框 -->
    <el-dialog
      title="修改角色"
      :before-close="handleDialogClose"
      :visible.sync="dialogTableRoleVisible"
      :destroy-on-close="!dialogTableRoleVisible"
    >
    <el-form
        label-width="auto"
        :model="userInfo"
        :label-position="position"
        ref="userForm"
        required-asterisk
        :rules="roleRules"
        center
      >
      <el-form-item required label="角色设置：">
          <el-select v-model="roleList" placeholder="选择角色" value-key="id" multiple size="medium" clearable>
          <el-option
            v-for="item in roleOptions"
            :key="item.id"
            :label="item.name"
            :value="{id:item.id,name:item.name}"
          ></el-option>
        </el-select>
        </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handlerRoleSave" size="medium" plain>保存</el-button>
        <el-button size="medium" @click="handleDialogClose" plain>取 消</el-button>
      </div>
    </el-dialog>
  </d2-container>
</template>
<script>
import { MessageBox } from 'element-ui'
export default {
  name: 'user',
  data () {
    return {
      // 遮罩层
      roleLoading: true,
      menuLoading: true,
      pageSize: [5, 10, 20, 50],
      /**
       * 检索条件
       */
      searchInfo: {
        // 当前页数
        currentPage: 1,
        // 每页条数
        limit: 5,
        // 列表总数
        total: 0,
        // 搜索框
        name: null,
        deptId: null
      },
      position: 'left',
      // 启用选项
      isEnabledOptions: [{ value: 'y', desc: '启用' }, { value: 'n', desc: '禁用' }],
      /** 菜单树 */
      menuTreeData: [],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      // 部门树
      deptTreeData: [],
      dialogTableVisible: false,
      dialogTableRoleVisible: false,
      /** 用户信息 */
      userInfo: {
        id: '',
        name: '',
        password: null,
        status: 'y',
        deptId: ''
      },
      // 角色信息
      roleInfo: {
        id: '',
        name: ''
      },
      roleList: [],
      roleOptions: [],
      // 校验
      roleRules: {
        name: [{ required: true, message: '请输入用户名称', trigger: 'blur' }]
      },
      // 是否修改
      isUpdate: false,
      /** 列表 */
      userList: [],
      // 是否保存
      isMenuSave: true,
      // 当前树形选中的info
      clickCurrentData: {}
    }
  },
  created () {
    this.getPage(this.searchInfo)
    this.getDeptTree()
  },
  methods: {
    /**
     * 角色信息
     */
    getPage (pageInfo) {
      const { currentPage, limit, ...data } = pageInfo
      this.roleLoading = true
      this.$api.USER_LIST_PAGE({ currentPage, limit, data })
        .then((result) => {
          this.userList = result.list
          this.searchInfo.total = Number(result.total)
          this.roleLoading = false
        })
        .catch()
    },
    /**
     * 树形，选择器
     */
    normalizer (node) {
      // 去掉children=[]的children属性
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    /** 部门树 */
    getDeptTree () {
      this.$api.DEPT_LIST_ALL()
        .then((res) => {
          this.deptTreeData = res
        })
        .catch()
    },
    /**
     * 初始化角色信息
     */
    inituserInfo () {
      this.userInfo = {
        id: '',
        name: '',
        password: null,
        status: 'y',
        deptId: ''
      }
      this.roleList = []
    },
    handleSizeChange (sizePage) {
      this.searchInfo.limit = sizePage
      this.getPage(this.searchInfo)
      this.handleDialogClose()
    },
    handleCurrentChange (pageNum) {
      this.searchInfo.currentPage = pageNum
      this.getPage(this.searchInfo)
      this.handleDialogClose()
    },
    /**
     * 弹窗关闭
     */
    handleDialogClose () {
      this.inituserInfo()
      this.dialogTableVisible = false
      this.dialogTableRoleVisible = false
      this.isUpdate = false
      this.clickCurrentData = null
    },
    handleFlash () {
      this.searchInfo = {
        currentPage: 1,
        limit: 5,
        total: 0,
        name: null,
        deptId: null
      }
      this.getPage(this.searchInfo)
    },
    /**
     * 新增
     */
    handlerAddNew () {
      this.isUpdate = false
      this.dialogTableVisible = true
      this.inituserInfo()
    },
    /**
     * 保存
     */
    handlerSave () {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          if (this.isUpdate) {
            this.updateRole()
          } else {
            this.saveUser()
          }
        } else {
          this.$message.error('表单校验失败，请检查')
        }
      })
    },
    saveUser () {
      console.info(this.userInfo)
      this.$api.USER_ADD(this.userInfo)
        .then((result) => {
          this.$message.success('保存成功')
          this.getPage(this.searchInfo)
          this.handleDialogClose()
        })
        .catch()
    },
    /**
     * 修改
     */
    handlerEdit () {
      const info = this.$refs.userTable.selection
      if (info.length <= 0) {
        this.$message({
          message: '请选择',
          type: 'warning'
        })
      } else if (info.length > 1) {
        this.$message({
          message: '请选择(有且只有一个)',
          type: 'warning'
        })
      } else {
        const row = info[0]
        this.isView = false
        this.isUpdate = true
        this.userInfo = row
        this.dialogTableVisible = true
      }
    },
    updateRole () {
      this.$api.USER_UPDATE(this.userInfo)
        .then((result) => {
          this.$message.success('修改成功')
          this.getPage(this.searchInfo)
          this.handleDialogClose()
        })
        .catch()
    },
    /**
     * 修改
     */
    handlerUpdate (data) {
      this.isUpdate = true
      this.inituserInfo()
      this.userInfo = JSON.parse(JSON.stringify(data))
      this.dialogTableVisible = true
    },
    /**
     * 删除
     */
    handleDeleteIds () {
      const info = this.$refs.userTable.selection
      if (info.length <= 0) {
        this.$message({
          message: '请选择',
          type: 'warning'
        })
      } else if (info.length > 0) {
        MessageBox.confirm('是否删除该数据', '删除', {
          type: 'warning'
        }).then(() => {
          const ids = []
          console.log('info', info)
          info.forEach((item) => {
            ids.push(item.id)
          })
          this.deleteUser(ids)
        })
      }
    },
    /**
     * 删除
     */
    handlerRemove (data) {
      if (data) {
        MessageBox.confirm('是否删除当前数据', '删除', {
          type: 'warning'
        }).then(() => {
          const array = [data.id]
          this.deleteUser(array)
        })
      }
    },
    handleResetPassword (data) {
      if (data) {
        MessageBox.confirm('是否重置当前用户密码', '重置', {
          type: 'warning'
        }).then(() => {
          this.$api.USER_RESETPASSWORD(data)
            .then(() => {
              this.$message.success('重置成功')
              this.handleDialogClose()
            })
            .catch(() => {
              this.handleDialogClose()
            })
        })
      }
    },
    // 修改角色弹窗
    handleChangeRole (data) {
      this.dialogTableRoleVisible = true
      this.inituserInfo()
      this.userInfo = JSON.parse(JSON.stringify(data))
      this.$api.ROLE_FINDALL_USER(data.id)
        .then((res) => {
          res.forEach((item) => {
            const role = { id: item }
            this.roleList.push(role)
          })
        })
      // 第一次打开加载全部的角色
      if (!this.roleOptions.length) {
        this.$api.ROLE_FINDALL()
          .then((res) => {
            console.log(res)
            this.roleOptions = res
          })
      }
      console.log(data)
    },
    handlerRoleSave () {
      this.$api.ROLES_SET_USER({ user: this.userInfo, roles: this.roleList })
        .then(() => {
          this.$message.success('修改成功')
          this.handleDialogClose()
        })
    },
    deleteUser (ids) {
      if (ids.length > 0) {
        this.$api.USER_LIST_DELETE(ids)
          .then((result) => {
            this.$message.success('删除成功')
            this.handleDialogClose()
            this.getPage(this.searchInfo)
          })
          .catch()
      }
    },
    /** 表格 */
    roleTableRowClick (row, column, cell, event) {
      this.clickCurrentData = row
    }
  }
}
</script>

<style scoped  lang="scss">
.el-table__body tr.current-row > td {
  background-color: #e8f4ff;
}
.avue-crud__menu{
  display: flex;
  justify-content: space-between;
  height: 40px;
}
</style>
